package cn.cas.mango.service;

import cn.cas.mango.util.RenderDateUtil;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.indices.GetAliasResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
// 按照月对索引进行分区的接口
@Service
@Slf4j
public class PartitionIndexService {
  @Autowired
  ElasticsearchClient client;
  @Autowired
  ConfigService config;
  public String partitionIndex(String index, String startDate, String endDate) {
    String alias = config.getAliasIndex();
    if (Strings.isBlank(startDate) || Strings.isBlank(endDate)) {
      return alias;
    }
    String prefixIndex = index;
    return returnIndex(prefixIndex, startDate, endDate);
  }


  public String returnIndex(String prefixIndex, String startDate, String endDate) {
    String[] split = prefixIndex.split(",");
    List<String> monthsBetween = RenderDateUtil.getMonthsBetween(startDate, endDate);
    Set<String> ret = new HashSet<>();
    for (String pi: split) {
      ret.addAll(monthsBetween.stream().map(x -> pi + x).collect(Collectors.toList()));
    }

    Set<String> alias;
    try {
      alias = getAlias();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
    ret.retainAll(alias);
    return String.join(",", ret);
  }

  public  Set<String> getAlias() throws IOException {
    GetAliasResponse aliasResponse = client.indices().getAlias(r -> r.name(config.getAliasIndex()));
    return aliasResponse.result().keySet();
  }
}
